package cn.secuber.weing.message.provider;

import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Handler;
import android.text.ClipboardManager;
import android.text.Selection;
import android.text.Spannable;
import android.text.SpannableString;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import cn.secuber.weing.R;
import cn.secuber.weing.SealAppContext;
import cn.secuber.weing.message.DestructionMessage;
import cn.secuber.weing.message.DestructionMessage;
import io.rong.imkit.RongContext;
import io.rong.imkit.RongIM;
import io.rong.imkit.RongKitIntent;
import io.rong.imkit.emoticon.AndroidEmoji;
import io.rong.imkit.model.ProviderTag;
import io.rong.imkit.model.UIMessage;
import io.rong.imkit.utilities.OptionsPopupDialog;
import io.rong.imkit.widget.AutoLinkTextView;
import io.rong.imkit.widget.ILinkClickListener;
import io.rong.imkit.widget.LinkTextViewMovementMethod;
import io.rong.imkit.widget.provider.IContainerItemProvider;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Message;

/**
 * Created by Administrator on 2019/3/18.
 */
    @ProviderTag(messageContent = DestructionMessage.class, showReadState = true)
    public class DestructionMessageProvider extends IContainerItemProvider.MessageProvider<DestructionMessage>{
        private static final String TAG = "DestructionMessageItemProvider";

        private static class ViewHolder {
            AutoLinkTextView message;
            boolean longClick;
        }

        @Override
        public View newView(Context context, ViewGroup group) {
            View view = LayoutInflater.from(context).inflate(io.rong.imkit.R.layout.rc_item_text_message, null);

            cn.secuber.weing.message.provider.DestructionMessageProvider.ViewHolder holder = new cn.secuber.weing.message.provider.DestructionMessageProvider.ViewHolder();
            holder.message = (AutoLinkTextView) view.findViewById(android.R.id.text1);
            view.setTag(holder);
            return view;
        }

        @Override
        public Spannable getContentSummary(DestructionMessage data) {
            return null;
        }

        @Override
        public Spannable getContentSummary(Context context, DestructionMessage data) {
            if (data == null)
                return null;

            String content = data.getContent();
            if (content != null) {
                if (content.length() > 100) {
                    content = content.substring(0, 100);
                }
                return new SpannableString(AndroidEmoji.ensure(content));
            }
            return null;
        }

        @Override
        public void onItemClick(View view, int position, DestructionMessage content, UIMessage message) {

        }

        @Override
        public void onItemLongClick(final View view, int position, final DestructionMessage content, final UIMessage message) {

            cn.secuber.weing.message.provider.DestructionMessageProvider.ViewHolder holder = (cn.secuber.weing.message.provider.DestructionMessageProvider.ViewHolder) view.getTag();
            holder.longClick = true;
            if (view instanceof TextView) {
                CharSequence text = ((TextView) view).getText();
                if (text != null && text instanceof Spannable)
                    Selection.removeSelection((Spannable) text);
            }

            String[] items;

            long deltaTime = RongIM.getInstance().getDeltaTime();
            long normalTime = System.currentTimeMillis() - deltaTime;
            boolean enableMessageRecall = false;
            int messageRecallInterval = -1;
            boolean hasSent = (!message.getSentStatus().equals(Message.SentStatus.SENDING)) && (!message.getSentStatus().equals(Message.SentStatus.FAILED));

            try {
                enableMessageRecall = RongContext.getInstance().getResources().getBoolean(io.rong.imkit.R.bool.rc_enable_message_recall);
                messageRecallInterval = RongContext.getInstance().getResources().getInteger(io.rong.imkit.R.integer.rc_message_recall_interval);
            } catch (Resources.NotFoundException e) {
                e.printStackTrace();
            }
            if (hasSent
                    && enableMessageRecall
                    && (normalTime - message.getSentTime()) <= messageRecallInterval * 1000
                    && message.getSenderUserId().equals(RongIM.getInstance().getCurrentUserId())
                    && !message.getConversationType().equals(Conversation.ConversationType.CUSTOMER_SERVICE)
                    && !message.getConversationType().equals(Conversation.ConversationType.APP_PUBLIC_SERVICE)
                    && !message.getConversationType().equals(Conversation.ConversationType.PUBLIC_SERVICE)
                    && !message.getConversationType().equals(Conversation.ConversationType.SYSTEM)
                    && !message.getConversationType().equals(Conversation.ConversationType.CHATROOM)) {
                items = new String[] {view.getContext().getResources().getString(io.rong.imkit.R.string.rc_dialog_item_message_copy), view.getContext().getResources().getString(io.rong.imkit.R.string.rc_dialog_item_message_delete), view.getContext().getResources().getString(io.rong.imkit.R.string.rc_dialog_item_message_recall)};
            } else {
                items = new String[] {view.getContext().getResources().getString(io.rong.imkit.R.string.rc_dialog_item_message_copy), view.getContext().getResources().getString(io.rong.imkit.R.string.rc_dialog_item_message_delete)};
            }

            OptionsPopupDialog.newInstance(view.getContext(), items).setOptionsPopupDialogListener(new OptionsPopupDialog.OnOptionsItemClickedListener() {
                @Override
                public void onOptionsItemClicked(int which) {
                    if (which == 0) {
                        @SuppressWarnings("deprecation")
                        ClipboardManager clipboard = (ClipboardManager) view.getContext().getSystemService(Context.CLIPBOARD_SERVICE);
                        clipboard.setText(((DestructionMessage) content).getContent());
                    } else if (which == 1) {
                        RongIM.getInstance().deleteMessages(new int[] {message.getMessageId()}, null);
                    } else if (which == 2) {
                        RongIM.getInstance().recallMessage(message.getMessage(), getPushContent(view.getContext(), message));
                    }
                }
            }).show();
        }

        @Override
        public void bindView(final View v, int position, final DestructionMessage content, final UIMessage data) {
            cn.secuber.weing.message.provider.DestructionMessageProvider.ViewHolder holder = (cn.secuber.weing.message.provider.DestructionMessageProvider.ViewHolder) v.getTag();
            final AutoLinkTextView textView = holder.message;
            if (data.getMessageDirection() == Message.MessageDirection.SEND) {
                holder.message.setBackgroundResource(R.drawable.de_ic_bubble_right);
            } else {
                holder.message.setBackgroundResource(R.drawable.rc_ic_bubble_left_file);
            }

            textView.setText(content.getContent());
            textView.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
            textView.setTextColor(Color.parseColor("#808080"));
            holder.message.setMovementMethod(new LinkTextViewMovementMethod(new ILinkClickListener() {
                @Override
                public boolean onLinkClick(String link) {
                    RongIM.ConversationBehaviorListener listener = RongContext.getInstance().getConversationBehaviorListener();
                    boolean result = false;
                    if (listener != null) {
                        result = listener.onMessageLinkClick(v.getContext(), link);
                    }
                    if (listener == null || !result) {
                        String str = link.toLowerCase();
                        if (str.startsWith("http") || str.startsWith("https")) {
                            Intent intent = new Intent(RongKitIntent.RONG_INTENT_ACTION_WEBVIEW);
                            intent.setPackage(v.getContext().getPackageName());
                            intent.putExtra("url", link);
                            v.getContext().startActivity(intent);
                            result = true;
                        }
                    }
                    return result;
                }
            }));
        }
    }

